package com.cyh.pangu.offer;

public class Offer29 {


    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }

        int rows = matrix.length, columns = matrix[0].length;
        int[] order = new int[rows * columns];
        int index = 0;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;

        while (left <= right && top <= bottom) {
            System.out.println("index:"+index + ",left:" + left + ",right:" + right + ",top:" + top+ ",bottom:" + bottom);
            for (int column = left; column <= right; column ++) {
//                System.out.println("1:index:"+index + ",top:" + top + ",column:" + column);
                order[index++] = matrix[top][column];
            }
            for (int row = top+1; row <= bottom; row ++) {
//                System.out.println("2:index:"+index + ",row:" + row + ",right:" + right);
                order[index++] = matrix[row][right];
            }
            if (index >= rows * columns) {
                return order;
            }


            for (int column = right -1; column >= left; column --) {
//                System.out.println("3:index:"+index + ",bottom:" + bottom + ",column:" + column);

                order[index++] = matrix[bottom][column];
            }

            for (int row = bottom -1; row > top; row--) {
//                System.out.println("4:index:"+index + ",row:" + row + ",left:" + left);
                order[index++] = matrix[row][left];
            }

            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }

    public static void main(String[] args) {
//        int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        Offer29 offer29 = new Offer29();
        int[] order = offer29.spiralOrder(matrix);
        for (int o :order) {
            System.out.println(o);
        }
    }




}
